#include "tree/tree.h"

#include <stdio.h>

#include <queue>
#include <utility>

void reverseTree(TreeNode* tree)
{
    if (nullptr == tree)
        return;
    std::swap(tree->left, tree->right);
    reverseTree(tree->left);
    reverseTree(tree->right);
}

void preOrder(const TreeNode* tree)
{
    if (nullptr == tree)
        return;
    printf("%d ", tree->data);
    preOrder(tree->left);
    preOrder(tree->right);
}

void inOrder(const TreeNode* tree)
{
    if (nullptr == tree)
        return;
    preOrder(tree->left);
    printf("%d ", tree->data);
    preOrder(tree->right);
}

void postOrder(const TreeNode* tree)
{
    if (nullptr == tree)
        return;
    preOrder(tree->left);
    preOrder(tree->right);
    printf("%d ", tree->data);
}

TreeNode* createTreeForTest(const int arr[], const int n)
{
    if (n <= 0)
        return nullptr;

    std::queue<TreeNode*> q;
    TreeNode* tree = new TreeNode(arr[0]);
    q.push(tree);

    const int empty = -1;
    for (int i = 1; i < n;)
    {
        TreeNode* node = q.front();
        q.pop();
        // 处理左子树
        if (arr[i] != empty && i < n)
        {
            node->left = new TreeNode(arr[i]);
            q.push(node->left);
        }
        i++;

        // 处理右子树
        if (arr[i] != empty && i < n)
        {
            node->right = new TreeNode(arr[i]);
            q.push(node->right);
        }
        i++;
    }

    return tree;
}

void deleteTree(TreeNode*& tree)
{
    if (nullptr == tree)
        return;

    deleteTree(tree->left);
    deleteTree(tree->right);
    delete tree;
    tree = nullptr;
}